<template>
  <div>
    <p @click="onVisible">
      <slot name="trigger"></slot>
    </p>
    <el-dialog v-bind="{ ...dialogProps }" :model-value="visible">
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onHide">取消</el-button>
          <el-button type="primary" @click="onOk">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { DialogProps } from 'element-plus'
import { omit } from 'lodash'
import { reactive, defineProps, toRefs, defineEmits, onMounted, onBeforeUnmount, watch } from 'vue'
/**
 * dialog的显示和隐藏组件内部来控制
 */
interface Props extends Partial<DialogProps> {
  'trigger-ref'?: HTMLElement | null
}

const props: any = defineProps<Props>()
const dialogProps = omit(props, ['trigger-ref'])
const emits = defineEmits(['onOk'])
interface State {
  visible: boolean
}
const state: State = reactive({
  visible: false
})
const { visible } = toRefs(state)

onMounted(() => props['trigger-ref']?.addEventListener('click', onVisible))
onBeforeUnmount(() => props['trigger-ref']?.removeEventListener('click', onVisible))
watch(
  props.visible,
  () => {
    if (typeof props.visible === 'boolean') {
      state.visible = props.visible
    }
  },
  { immediate: true }
)
const onVisible = () => {
  if (props.onVisible) {
    return props.onVisible()
  }
  state.visible = true
}

const onHide = () => {
  if (props.onHide) {
    return props.onHide()
  }
  state.visible = false
}

const onOk = () => {
  emits('onOk')
  onHide()
}
</script>
